import axios from 'axios';
import gData from "@/util/globalData.js"
import Router from '@/router'//vue-router
import store from '@/store/index.js'
import {
    Message
} from 'element-ui';
axios.defaults.timeout = 5000;
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL; //填写域名
//http request 拦截器
axios.interceptors.request.use(config => {
	config.headers = {
	  'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': gData.getLocal('token') || '',
    'platform': 'web',
	  //'Content-Type':'multipart/form-data'
	}
	return config;
	},
	error => {
		return Promise.reject(err);
	}
);

//响应拦截器即异常处理
axios.interceptors.response.use(({status, data}) => {
	//console.log('response',response)
	if(status == 200){
    const { code, msg } = data;
    switch(code){
      case -1:
        const path = Router.history.current.path
        store.commit('app/changeRefresh', true) //是否刷新
			  Router.push(`/login?redirect=${path}`)
        break;
      case 0:
        Message.error(msg)
        break;
      default:
        return data;
    }
    if(code === -1){
      
    }else{
      
    }
		
	}else{
		console.log(data);
	}
	
}, err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          Message('错误请求400')
          break;
        case 401:
          Message('错误请求401')
          break;
        case 403:
          Message('拒绝访问403')
          break;
        case 404:
          Message('请求错误,未找到该资源404')
          break;
        case 405:
          Message('请求方法未允许405')
          break;
        case 408:
          Message('请求超时408')
          break;
        case 500:
          Message('服务器端出错500')
          break;
        case 501:
          Message('网络未实现501')
          break;
        case 502:
          Message('网络错误502')
          break;
        case 503:
          Message('服务不可用503')
          break;
        case 504:
          Message('网络超时504')
          break;
        case 505:
          Message('http版本不支持该请求505')
          break;
        default:
          Message(`未知错误${err.response.status}`)
      }
    } else {
		Message('连接到服务器失败')
    }
    return Promise.resolve(err.response)
})
export default axios